package com.edu.buaa;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    // 宫位布局数组
    private RelativeLayout[] palaceLayouts = new RelativeLayout[12];
    private TextView[] starTextViews = new TextView[12];
    private TextView[] nameTextViews = new TextView[12];
    private TextView[] branchTextViews = new TextView[12];

    // 个人信息视图
    private LinearLayout personalLayout;
    private TextView personalInfo1, personalInfo2;

    private TextView resultTextView;
    private List<Palace> palaces;
    private Palace selectedPalace;
    private TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        Log.d(TAG, "MainActivity onCreate");

        // 接收生辰数据
        Intent intent = getIntent();
        if (intent != null) {
            String gender = intent.getStringExtra("gender");
            int year = intent.getIntExtra("year", 1988);
            int month = intent.getIntExtra("month", 2);
            int day = intent.getIntExtra("day", 29);
            int hour = intent.getIntExtra("hour", 2);
            String solarDate = intent.getStringExtra("solar_date");

            // 更新个人信息显示
            updatePersonalInfoWithBirthData(gender, year, month, day, hour, solarDate);
        }

        try {
            initData();
            setupClickListeners();
            updateAllPalaces();
            Log.d(TAG, "MainActivity initialized successfully");
        } catch (Exception e) {
            Log.e(TAG, "Error initializing MainActivity: " + e.getMessage(), e);
            Toast.makeText(this, "排盘页面初始化失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 创建菜单
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            // 返回按钮被点击
            goBackToBirthInput();
            return true;
        } else if (id == R.id.action_logout) {
            // 退出登录
            logout();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        // 物理返回键也返回生辰输入页面
        goBackToBirthInput();
    }

    private void goBackToBirthInput() {
        Intent intent = new Intent(MainActivity.this, BirthInputActivity.class);
        startActivity(intent);
        finish();
    }

    private void logout() {
        // 清除登录状态
        SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();

        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();

        // 跳转到登录页面
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    // 新增方法：使用生辰数据更新个人信息
    private void updatePersonalInfoWithBirthData(String gender, int year, int month, int day, int hour, String solarDate) {
        String[] hourNames = {"子时", "丑时", "寅时", "卯时", "辰时", "巳时",
                "午时", "未时", "申时", "酉时", "戌时", "亥时"};

        String hourText = hourNames[hour] + " (" + getHourTimeRange(hour) + ")";

        personalInfo1.setText("性别: " + gender + "\n生日: 阳历" + solarDate + "\n" + hourText);

        // 这里可以添加四柱推算逻辑
        String fourPillars = calculateFourPillars(year, month, day, hour);
        String fiveElements = calculateFiveElements(fourPillars);

        personalInfo2.setText("四柱: " + fourPillars + "\n五行: " + fiveElements);
    }

    private String getHourTimeRange(int hour) {
        String[] ranges = {
                "23:00-00:59", "01:00-02:59", "03:00-04:59", "05:00-06:59",
                "07:00-08:59", "09:00-10:59", "11:00-12:59", "13:00-14:59",
                "15:00-16:59", "17:00-18:59", "19:00-20:59", "21:00-22:59"
        };
        return ranges[hour];
    }

    // 简化的四柱推算（实际需要完整的农历转换和天干地支计算）
    private String calculateFourPillars(int year, int month, int day, int hour) {
        // 这里应该是完整的四柱推算逻辑
        // 简化版本，返回固定值
        return "戊辰 甲寅 甲寅 丙寅";
    }

    private String calculateFiveElements(String fourPillars) {
        // 五行计算逻辑
        // 简化版本
        return "木三 火二 土一 金〇 水〇";
    }

    private void initViews() {
        // 初始化宫位布局数组
        palaceLayouts[0] = findViewById(R.id.palace_layout_0);
        palaceLayouts[1] = findViewById(R.id.palace_layout_1);
        palaceLayouts[2] = findViewById(R.id.palace_layout_2);
        palaceLayouts[3] = findViewById(R.id.palace_layout_3);
        palaceLayouts[4] = findViewById(R.id.palace_layout_4);
        palaceLayouts[5] = findViewById(R.id.palace_layout_5);
        palaceLayouts[6] = findViewById(R.id.palace_layout_6);
        palaceLayouts[7] = findViewById(R.id.palace_layout_7);
        palaceLayouts[8] = findViewById(R.id.palace_layout_8);
        palaceLayouts[9] = findViewById(R.id.palace_layout_9);
        palaceLayouts[10] = findViewById(R.id.palace_layout_10);
        palaceLayouts[11] = findViewById(R.id.palace_layout_11);

        // 初始化星曜文本视图
        starTextViews[0] = findViewById(R.id.palace_0_star);
        starTextViews[1] = findViewById(R.id.palace_1_star);
        starTextViews[2] = findViewById(R.id.palace_2_star);
        starTextViews[3] = findViewById(R.id.palace_3_star);
        starTextViews[4] = findViewById(R.id.palace_4_star);
        starTextViews[5] = findViewById(R.id.palace_5_star);
        starTextViews[6] = findViewById(R.id.palace_6_star);
        starTextViews[7] = findViewById(R.id.palace_7_star);
        starTextViews[8] = findViewById(R.id.palace_8_star);
        starTextViews[9] = findViewById(R.id.palace_9_star);
        starTextViews[10] = findViewById(R.id.palace_10_star);
        starTextViews[11] = findViewById(R.id.palace_11_star);

        // 初始化宫名文本视图
        nameTextViews[0] = findViewById(R.id.palace_0_name);
        nameTextViews[1] = findViewById(R.id.palace_1_name);
        nameTextViews[2] = findViewById(R.id.palace_2_name);
        nameTextViews[3] = findViewById(R.id.palace_3_name);
        nameTextViews[4] = findViewById(R.id.palace_4_name);
        nameTextViews[5] = findViewById(R.id.palace_5_name);
        nameTextViews[6] = findViewById(R.id.palace_6_name);
        nameTextViews[7] = findViewById(R.id.palace_7_name);
        nameTextViews[8] = findViewById(R.id.palace_8_name);
        nameTextViews[9] = findViewById(R.id.palace_9_name);
        nameTextViews[10] = findViewById(R.id.palace_10_name);
        nameTextViews[11] = findViewById(R.id.palace_11_name);

        // 初始化地支文本视图
        branchTextViews[0] = findViewById(R.id.palace_0_branch);
        branchTextViews[1] = findViewById(R.id.palace_1_branch);
        branchTextViews[2] = findViewById(R.id.palace_2_branch);
        branchTextViews[3] = findViewById(R.id.palace_3_branch);
        branchTextViews[4] = findViewById(R.id.palace_4_branch);
        branchTextViews[5] = findViewById(R.id.palace_5_branch);
        branchTextViews[6] = findViewById(R.id.palace_6_branch);
        branchTextViews[7] = findViewById(R.id.palace_7_branch);
        branchTextViews[8] = findViewById(R.id.palace_8_branch);
        branchTextViews[9] = findViewById(R.id.palace_9_branch);
        branchTextViews[10] = findViewById(R.id.palace_10_branch);
        branchTextViews[11] = findViewById(R.id.palace_11_branch);

        // 初始化个人信息视图
        personalLayout = findViewById(R.id.personal_layout);
        personalInfo1 = findViewById(R.id.personal_info_1);
        personalInfo2 = findViewById(R.id.personal_info_2);

        resultTextView = findViewById(R.id.resultTextView);

        // 标题栏按钮
        Button btnBack = findViewById(R.id.btnBack);
        Button btnLogout = findViewById(R.id.btnLogout);

        // 标题栏
        tvTitle = findViewById(R.id.tvTitle);
        // 设置标题
        tvTitle.setText("紫微斗数排盘");

        // 设置按钮点击事件
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBackToBirthInput();
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }

    // 其他方法保持不变...
    private void initData() {
        palaces = new ArrayList<>();

        // 初始化12宫位数据
        palaces.add(new Palace("交友宫", "巨门", "奴仆", "", "", "交友宫主人际关系"));
        palaces.add(new Palace("迁移宫", "廉贞\n天相", "迁移", "丁", "巳", "迁移宫主外出发展"));
        palaces.add(new Palace("疾厄宫", "天梁", "疾厄", "戊", "午", "疾厄宫主健康疾病"));
        palaces.add(new Palace("财帛宫", "七杀", "财帛", "己未", "庚申", "财帛宫主财富积累"));
        palaces.add(new Palace("官禄宫", "贪狼", "官禄", "丙", "辰", "官禄宫主事业工作"));
        palaces.add(new Palace("子女宫", "天同\n武曲", "子女\n夫妻", "辛酉", "壬戌", "子女宫主子女运势"));
        palaces.add(new Palace("田宅宫", "太阴", "田宅", "乙", "卯", "田宅宫主房产家业"));
        palaces.add(new Palace("夫妻宫", "", "夫妻", "", "", "夫妻宫主婚姻感情"));
        palaces.add(new Palace("福德宫", "紫微\n天府", "福德", "甲", "寅", "福德宫主精神修养"));
        palaces.add(new Palace("父母宫", "天机", "父母", "乙", "丑", "父母宫主父母关系"));
        palaces.add(new Palace("命宫", "破军", "命宫", "甲", "子", "命宫主一生基础运势"));
        palaces.add(new Palace("兄弟宫", "太阳", "兄弟", "癸", "亥", "兄弟宫主兄弟姐妹关系"));
    }

    private void setupClickListeners() {
        for (int i = 0; i < palaceLayouts.length; i++) {
            final int position = i;
            palaceLayouts[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectPalace(position);
                }
            });
        }

        // 个人信息区域点击事件
        personalLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPersonalInfo();
            }
        });
    }

    private void showPersonalInfo() {
        String personalInfo = "个人信息\n\n" +
                "性别: 女\n" +
                "生日: 阳历1988年2月29日 03:00-04:59\n" +
                "四柱: 戊辰 甲寅 甲寅 丙寅\n" +
                "五行: 木三 火二 土一 金〇 水〇\n\n" +
                "命主: 破军\n" +
                "身主: 文昌";

        resultTextView.setText(personalInfo);

        // 添加动画效果
        resultTextView.animate()
                .scaleX(1.05f)
                .scaleY(1.05f)
                .setDuration(200)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        resultTextView.animate()
                                .scaleX(1f)
                                .scaleY(1f)
                                .setDuration(200);
                    }
                });
    }

    private void updateAllPalaces() {
        for (int i = 0; i < palaces.size(); i++) {
            updatePalaceDisplay(i);
        }

        // 更新个人信息
        updatePersonalInfo();
    }

    private void updatePalaceDisplay(int position) {
        Palace palace = palaces.get(position);

        // 更新星曜
        String starsText = palace.getStars();
        starTextViews[position].setText(starsText);

        // 更新宫名
        String nameText = palace.getPosition();
        nameTextViews[position].setText(nameText);

        // 更新地支
        String branchText = palace.getBranchDisplay();
        branchTextViews[position].setText(branchText);

        // 根据内容长度动态调整字体大小
        adjustTextSize(starTextViews[position], starsText);
        adjustTextSize(nameTextViews[position], nameText);
        adjustTextSize(branchTextViews[position], branchText);

        // 更新高亮状态
        if (palace.isHighlighted()) {
            palaceLayouts[position].setBackgroundResource(R.drawable.highlight_border);
        } else {
            palaceLayouts[position].setBackgroundResource(R.drawable.border);
        }
    }

    private void adjustTextSize(TextView textView, String text) {
        if (text == null || text.isEmpty()) return;

        int lineCount = text.split("\n").length;
        int textLength = text.length();

        // 根据文本长度和行数调整字体大小
        if (lineCount > 3 || textLength > 15) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
        } else if (lineCount > 2 || textLength > 10) {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f);
        } else {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);
        }
    }

    private void updatePersonalInfo() {
        personalInfo1.setText("性别: 女\n生日: 阳历1988年2月29日\n03:00-04:59");
        personalInfo2.setText("四柱: 戊辰 甲寅 甲寅 丙寅\n五行: 木三 火二 土一 金〇 水〇");
    }

    private void selectPalace(int position) {
        // 取消之前的高亮
        if (selectedPalace != null) {
            selectedPalace.setHighlighted(false);
            // 找到之前高亮的宫位并更新显示
            for (int i = 0; i < palaces.size(); i++) {
                if (palaces.get(i) == selectedPalace) {
                    updatePalaceDisplay(i);
                    break;
                }
            }
        }

        // 设置新高亮
        Palace palace = palaces.get(position);
        palace.setHighlighted(true);
        selectedPalace = palace;

        // 更新显示
        updatePalaceDisplay(position);

        // 显示推算结果
        showCalculationResult(palace);
    }

    private void showCalculationResult(Palace palace) {
        String result = generateCalculationResult(palace);
        resultTextView.setText(result);

        // 添加动画效果
        resultTextView.animate()
                .scaleX(1.05f)
                .scaleY(1.05f)
                .setDuration(200)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        resultTextView.animate()
                                .scaleX(1f)
                                .scaleY(1f)
                                .setDuration(200);
                    }
                });
    }

    private String generateCalculationResult(Palace palace) {
        if (palace.getName().isEmpty()) {
            return "请选择宫位查看详细推算...";
        }

        return "宫位: " + palace.getName() + "\n\n" +
                "主星: " + palace.getStars() + "\n\n" +
                "位置: " + palace.getPosition() + "\n\n" +
                "天干地支: " + palace.getHeavenlyStem() + palace.getEarthlyBranch() + "\n\n" +
                "详细解读:\n" + palace.getDescription() + "\n\n" +
                "运势分析: 当前运势平稳，建议...\n\n" +
                "吉凶指数: ★★★☆☆";
    }

    // 动态修改宫位内容的方法
    public void updatePalaceContent(int palaceIndex, String newStars, String newPosition, String newHeavenlyStem, String newEarthlyBranch, String newDescription) {
        if (palaceIndex >= 0 && palaceIndex < palaces.size()) {
            Palace palace = palaces.get(palaceIndex);

            // 创建新的 Palace 对象来更新内容
            Palace updatedPalace = new Palace(
                    palace.getName(),
                    newStars != null ? newStars : palace.getStars(),
                    newPosition != null ? newPosition : palace.getPosition(),
                    newHeavenlyStem != null ? newHeavenlyStem : palace.getHeavenlyStem(),
                    newEarthlyBranch != null ? newEarthlyBranch : palace.getEarthlyBranch(),
                    newDescription != null ? newDescription : palace.getDescription()
            );

            // 保持高亮状态
            updatedPalace.setHighlighted(palace.isHighlighted());

            // 更新列表
            palaces.set(palaceIndex, updatedPalace);

            // 如果是当前选中的宫位，更新选中引用
            if (selectedPalace == palace) {
                selectedPalace = updatedPalace;
            }

            // 更新显示
            updatePalaceDisplay(palaceIndex);

            // 如果这个宫位是当前选中的，也更新结果
            if (selectedPalace == updatedPalace) {
                showCalculationResult(updatedPalace);
            }
        }
    }

    // 更新个人信息的方法
    public void updatePersonalInfo(String birthday, String fourPillars, String fiveElements) {
        personalInfo1.setText("性别: 女\n生日: " + birthday);
        personalInfo2.setText("四柱: " + fourPillars + "\n五行: " + fiveElements);
    }

    // 示例：添加测试按钮来演示更新功能
    public void onTestUpdate(View view) {
        // 更新命宫（位置10）
        updatePalaceContent(10, "破军\n禄存", "命宫", "甲", "子", "命宫主一生基础运势，破军化禄，主变动中得财");

        // 更新财帛宫（位置3）
        updatePalaceContent(3, "七杀\n文昌", "财帛", "己未", "庚申", "财帛宫主财富积累，七杀主偏财，文昌主文财");

        Toast.makeText(this, "已更新命宫和财帛宫", Toast.LENGTH_SHORT).show();
    }
}